package luke4fun.wheresmymoney.service.async;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;

import java.util.ArrayList;
import java.util.List;

import luke4fun.wheresmymoney.adapter.list.BasicAdapter;
import luke4fun.wheresmymoney.bean.CategoryBean;
import luke4fun.wheresmymoney.db.AccDBHelper;
import luke4fun.wheresmymoney.db.CategoryDAO;
import luke4fun.wheresmymoney.domain.Category;

public class CategoryAsyncTask extends AsyncTask<Integer, String, List<CategoryBean>> {

	private AccDBHelper dbHelper;
	private SQLiteDatabase db;
	private BasicAdapter<CategoryBean> adapter;
	
	public CategoryAsyncTask(Context context, BasicAdapter<CategoryBean> adapter) {
		dbHelper = new AccDBHelper(context);
		this.adapter = adapter; 
	}

	@Override
	protected List<CategoryBean> doInBackground(Integer... params) {
		CategoryDAO dao = CategoryDAO.getInstance();
		
		db = dbHelper.getReadableDatabase();
		List<Category> list = dao.queryCategory(db, null);

		List<CategoryBean> beanList = new ArrayList<CategoryBean>();
		for (Category c : list) {
			CategoryBean bean = new CategoryBean();
			bean.setId(c.getId());
			bean.setName(c.getName());
			bean.setColor(c.getColor());
			bean.setFrequence(c.getFrequence());
			
			beanList.add(bean);
		}
		
		db.close();
		dbHelper.close();
		return beanList;
	}

	@Override
	protected void onPostExecute(List<CategoryBean> result) {
		adapter.updateList(result);
	}
}
